#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.dev'

import django
django.setup()

import time, hashlib, base64, json, requests, datetime, openpyxl, smtplib
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import algorithms
from random import Random
from Crypto.Cipher import AES
import urllib.parse
from decimal import Decimal
from django.db import transaction
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from django.utils.encoding import escape_uri_path
from django.db.models import Sum

from users.models import Level, User, CustomerUser
from merchants.models import Merchant, MerchantEnter, MerchantChannel, MerchantImage, MerchantUser, MerchantBill, MerchantBillPushDate
from activities.models import Activity, ActivityLevel, ActivityLevelRecord, PointRecord,Channel
from goods.models import *
from orders.models import *
from equity_mall.utils.qiniu_storage import pic_upload
from vouchers.models import *
from equity_mall.utils.sync_img_to_local import sync_img_to_local, make_qrcode
from random import randint
from cashbonus.models import *
from equity_mall.utils.utils import ryx_settle_order_wx, check_shop_can_subsidy


def get_sign(data_dict, secret):
    params_list = sorted(data_dict.items(), key=lambda e: e[0], reverse=False)
    params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list) + '&secret=' + secret
    md5 = hashlib.md5()
    md5.update(params_str.encode('utf-8'))
    sign = md5.hexdigest().upper()
    return sign


def pkcs7_padding(data):
    if not isinstance(data, bytes):
        data = data.encode()
    padder = padding.PKCS7(algorithms.AES.block_size).padder()
    padded_data = padder.update(data) + padder.finalize()
    return padded_data


def encrypt(text, key, iv):
    key = key.encode('utf-8')
    iv = iv.encode('utf-8')
    mode = AES.MODE_CBC
    cryptos = AES.new(key, mode, iv)
    text = pkcs7_padding(text.encode('utf-8'))
    cipher_text = cryptos.encrypt(text)
    return base64.b64encode(cipher_text).decode('utf-8')


def decrypt(text, key, iv):
    key = key.encode('utf-8')
    iv = iv.encode('utf-8')
    text = base64.b64decode(text.encode('utf8'))
    mode = AES.MODE_CBC
    cryptor = AES.new(key, mode, iv)
    plain_text = cryptor.decrypt(text)
    return bytes.decode(plain_text).rstrip('\0').rstrip("\x01").rstrip("\x02").rstrip("\x03").rstrip("\x04").rstrip("\x05").rstrip("\x06").rstrip("\x07").rstrip("\x08").rstrip("\x09").rstrip("\x0a").rstrip("\x0b").rstrip("\x0c").rstrip("\x0d").rstrip("\x0e").rstrip("\x0f").rstrip("\x10")


def random_str(randomlength=32):
    strs = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        strs += chars[random.randint(0, length)]
    return strs


def get_result(method, body):
    key = 'cw8jYudat!fHKnLkpsTm^VJ&5PylBMW7'
    iv = 'acOtV2Bb3QZIJYdR'
    secret = 'Alp$muNw&dT3RPy1onDsMkG86hBOYLDf'
    token = Channel.objects.get(id=5).cookie
    timestamp = str(int(time.time()))
    nonce = random_str()
    data_dict = {'method': method}
    data = encrypt(json.dumps(body).replace(' ', ''), key, iv)
    data_dict['data'] = data
    data_dict['nonce'] = nonce
    data_dict['timestamp'] = timestamp
    signture = get_sign(data_dict, secret)
    headers = {
        'company-token': token,
        'sign-app-nonce': nonce,
        'sign-app-signture': signture,
        'sign-app-timestamp': timestamp
    }
    url = f'https://i.wxmas.com/company-gateway/api?data={urllib.parse.quote(data)}&method={method}'
    response = requests.get(url=url, headers=headers)
    return decrypt(response.json()['data'], key, iv)


def post_result(method, body):
    key = 'cw8jYudat!fHKnLkpsTm^VJ&5PylBMW7'
    iv = 'acOtV2Bb3QZIJYdR'
    secret = 'Alp$muNw&dT3RPy1onDsMkG86hBOYLDf'
    token = Channel.objects.get(id=5).cookie
    timestamp = str(int(time.time()))
    nonce = random_str()
    data_dict = {'method': method}
    data = encrypt(json.dumps(body).replace(' ', ''), key, iv)
    data_dict['data'] = data
    data_dict['nonce'] = nonce
    data_dict['timestamp'] = timestamp
    signture = get_sign(data_dict, secret)
    headers = {
        'company-token': token,
        'sign-app-nonce': nonce,
        'sign-app-signture': signture,
        'sign-app-timestamp': timestamp,
        'content-type': 'application/json'
    }
    url = 'https://i.wxmas.com/company-gateway/api'
    response = requests.post(url=url, headers=headers, data=json.dumps({'data': data, 'method': method}))
    return decrypt(response.json()['data'], key, iv)


def login_qrcode_result(method, body):
    key = 'X7ALsOPM09ZeyJTUfHGcnuqb5QmNjx3R'
    iv = 'JlrwG2XYCy4AHOx9'
    secret = 'RNfDp7n3eWGmP1LiHxTzqv5YK96S8BQb'
    token = Channel.objects.get(id=5).token
    timestamp = str(int(time.time()))
    nonce = random_str()
    data_dict = {'method': method}
    data = encrypt(json.dumps(body).replace(' ', ''), key, iv)
    data_dict['data'] = data
    data_dict['nonce'] = nonce
    data_dict['timestamp'] = timestamp
    signture = get_sign(data_dict, secret)
    headers = {
        'Authorization': token,
        'sign-app-nonce': nonce,
        'sign-app-signture': signture,
        'sign-app-timestamp': timestamp,
        'content-type': 'application/json'
    }
    url = 'https://ministaff.wxmas.com/mini-staff-gateway/api'
    response = requests.post(url=url, headers=headers, data=json.dumps({'data': data, 'method': method}))
    return decrypt(response.json()['data'], key, iv)


def pull_ri_companyuser():
    print('%s: pull_ri_companyuser' % time.ctime())
    method = 'companyUserList'
    page = 1
    is_break = 0
    while True:
        body = {"page": str(page), 'pageSize': '1000'}
        if is_break:
            break
        result = json.loads(get_result(method, body))['data']['manageList']
        if not result:
            break
        for i in result:
            user_data = {}
            user_data['wyh_id'] = i['id']
            user_data['username'] = i['name']
            user_data['nickname'] = i['name']
            user_data['mobile'] = i['phone']
            user_data['platform'] = 2
            user_data['role_id'] = 3
            user_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
            if i['isUse']:
                user_data['is_active'] = 1
            else:
                user_data['is_active'] = 0
            try:
                level = Level.objects.filter(orgId=i['orgIds'][0]).first()
                user_data['OrgId'] = i['orgIds'][0]
                if level:
                    user_data['level_id'] = level.id
            except:
                pass
            user_data['account'] = i['jobNumber']
            try:
                instance, create = User.objects.get_or_create(mobile=user_data['mobile'], defaults=user_data)
                if create:
                    print(instance.id)
            except:
                print(i['phone'])
        page += 1


def pull_ri_merchant():
    print('%s: pull_ri_merchant' % time.ctime())
    method = 'SupplierList'
    # body = {"page": '1', 'pageSize': '10'}
    # print(post_result(method, body))
    is_break = 0
    page = 1
    while True:
        body = {"page": str(page), 'pageSize': '1000'}
        print(body)
        if is_break:
            break
        result = json.loads(get_result(method, body))['data']['list']
        if not result:
            break
        for i in result:
            user_data = {}
            enter_data = {}
            enter_data['id'] = i['id']
            user_data['name'] = i['name']
            user_data['managerName'] = i['managerName']
            user_data['managermobile'] = i['managerMobile']
            user_data['wyfMerchantID'] = i['wyfMerchantID']
            user_data['ruiyinxinMerchantID'] = i['ruiyinxinMerchantID']
            enter_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
            user_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')

            try:
                instance, create = Merchant.objects.get_or_create(wyfMerchantID=user_data['wyfMerchantID'], defaults=user_data)
                if create:
                    print(instance.id)
                enter_data['merchant_id'] = instance.id
                try:
                    level = Level.objects.filter(orgId=i['orgID']).first()
                    enter_data['OrgId'] = i['orgID']
                    if level:
                        enter_data['level_id'] = level.id
                except:
                    pass
                enter, create = MerchantEnter.objects.get_or_create(merchant_id=enter_data['merchant_id'], level_id=enter_data['level_id'], defaults=enter_data)
            except Exception as e:
                print(i['managerMobile'])
        page += 1


def pull_ri_activity():
    print('%s: pull_ri_activity' % time.ctime())
    method = 'GiftBagPointGetActivityList'
    # body = {"page": '1', 'pageSize': '1'}
    # print(get_result(method, body))
    is_break = 0
    page = 1
    while True:
        if is_break:
            break
        body = {"page": str(page), 'pageSize': '100'}
        result = json.loads(get_result(method, body))['data']['activityList']
        if not result:
            break
        for i in result:
            user_data = {}
            user_data['activity_id'] = i['id']
            user_data['name'] = i['name']
            user_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
            user_data['platform'] = 2
            user_data['available_begin_time'] = i['timeRule']['startedAt'].replace('T', ' ').replace('+08:00', '')
            user_data['available_end_time'] = i['timeRule']['endedAt'].replace('T', ' ').replace('+08:00', '')
            user_data['max_point'] = i['totalPoint']
            user_data['distributed_point'] = i['receivePoint']
            try:
                level = Level.objects.filter(orgId=i['orgId']).first()
                user_data['OrgId'] = i['orgId']
                if level:
                    level.point += int(i['totalPoint'])
                    level.save()
                    user_data['level_id'] = level.id
            except:
                pass
            try:
                user = User.objects.filter(orgId=i['wyh_id']['userId']).first()
                if user:
                    user_data['create_user_id'] = user.id
                else:
                    user_id=None
            except:
                user_id=None
            try:
                instance, create = Activity.objects.update_or_create(activity_id=user_data['activity_id'], defaults=user_data)
                if create:
                    print(instance.id)
                    activity_level = ActivityLevel.objects.create(
                        level_id=instance.level_id,
                        activity_id=instance.id,
                        max_point=instance.max_point
                    )
                    ActivityLevelRecord.objects.create(
                        activity_level_id=activity_level.id,
                        point=activity_level.max_point,
                        operation_type=1,
                        user_id=user_id,
                        create_time=i['createdAt'].replace('T', ' ').replace('+08:00', ''),
                        level_id=instance.level_id,
                    )
                # else:
                #     is_break = 1
                #     break
            except:
                print(i['name'])
        page += 1


def pull_point_record():
    print('%s: pull_point_record' % time.ctime())
    method = 'GiftBagPointGetAllotRecordList'
    body = {"page":"1","pageSize":"10","source":"allot","actId":"282101895965851648","orgId":"176044788054528000"}
    print(get_result(method, body))
    # query_set = ActivityLevel.objects.all()
    # for instance in query_set:
    #     level = instance.level
    #     body = {"page": "1", "pageSize": "10", "source": "allot", "actId": "282101895965851648", "orgId": level.orgId}
    #     result = json.loads(get_result(method, body))['data']['recordList']


def pull_ri_user():
    print('%s: pull_ri_user' % time.ctime())
    method = 'MemberList'
    # body = {"page": '1', 'pageSize': '10'}
    # print(get_result(method, body))
    is_break = 0
    page = 1
    while True:
        if is_break:
            break
        body = {"page": str(page), 'pageSize': '10', 'openId': 'oI_D75XzTUiAIuV9dEb9fJ5HEKGQ'}
        print(body)
        result = json.loads(get_result(method, body))['data']['list']
        if not result:
            break
        for i in result:
            user_data = {}
            # user_data['user_id'] = i['Id']
            user_data['mobile'] = i['Mobile']
            user_data['old_openid'] = i['Openid']
            user_data['is_distributor'] = i['isDistributor']
            user_data['idcode'] = i['idcode']
            user_data['realname'] = i['realname']
            user_data['username'] = i['nickname']
            user_data['address'] = i['address']
            user_data['is_offline'] = i['offlineMember']
            user_data['point'] = i['localpoint']
            user_data['avatar'] = i['avatar']
            user_data['create_time'] = i['CreatedAt'].replace('T', ' ').replace('+08:00', '')
            try:
                instance, create = CustomerUser.objects.update_or_create(mobile=user_data['mobile'], defaults=user_data)
                if create:
                    print(instance.id)
                # else:
                #     is_break = 1
                #     break
            except Exception as e:
                print(i['Mobile'], e)
        page += 1


def pull_merchant(wyfMerchantID):
    print('%s: pull_ri_merchant' % time.ctime())
    method = 'SupplierList'
    # body = {"page": '1', 'pageSize': '10'}
    # print(post_result(method, body))
    body = {"page": '1', 'pageSize': '1', "ruiyinxinMerchantID": wyfMerchantID}
    result = json.loads(get_result(method, body))['data']['list']
    i = result[0]
    user_data = {}
    enter_data = {}
    enter_data['id'] = i['id']
    user_data['name'] = i['name']
    user_data['managerName'] = i['managerName']
    user_data['managermobile'] = i['managerMobile']
    user_data['wyfMerchantID'] = i['wyfMerchantID']
    user_data['ruiyinxinMerchantID'] = i['ruiyinxinMerchantID']
    enter_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
    user_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
    instance, create = Merchant.objects.get_or_create(wyfMerchantID=user_data['wyfMerchantID'], defaults=user_data)
    if create:
        print(instance.id)
    enter_data['merchant_id'] = instance.id
    try:
        level = Level.objects.filter(orgId=i['orgID']).first()
        enter_data['OrgId'] = i['orgID']
        if level:
            enter_data['level_id'] = level.id
    except:
        pass
    enter, create = MerchantEnter.objects.get_or_create(merchant_id=enter_data['merchant_id'], level_id=enter_data['level_id'], defaults=enter_data)
    return instance


def pull_goods(id, business_no):
    # print('%s: pull_ri_goods' % time.ctime())
    method = 'EquityGoodsList'
    body = {"page":"1","pageSize":"10","id":id,"searchPointActIds":[]}
    result = json.loads(get_result(method, body))['data']
    i = result['list'][0]
    user_data = {}
    goods_id = int(i['id']) + 10000000
    user_data['id'] = goods_id
    user_data['name'] = i['name']
    user_data['create_time'] = i['createdAt'].replace('T', ' ').replace('+08:00', '')
    user_data['equityID'] = i['id']
    user_data['price'] = Decimal(i['exchangeNumber']) / 100
    user_data['cost_price'] = Decimal(i['exchangeNumber']) / 100
    user_data['market_price'] = Decimal(i['exchangeNumber']) / 100
    default_image = f'youhuiquanyi/{i["supplierDetail"]["wyfMerchantID"]}/default_image{goods_id}.png'
    if i['images'] and 'http' in i['images'][0]['url']:
        pic_upload(requests.get(i['images'][0]['url']).content, key=default_image)
    user_data['default_image'] = default_image
    user_data['desc_detail'] = i['detail']
    user_data['category_id'] = 1
    user_data['is_launched'] = 0
    try:
        merchant = Merchant.objects.filter(wyfMerchantID=str(business_no)).first()
        if merchant:
            user_data['merchant_id'] = merchant.id
        else:
            merchant = pull_merchant(wyfMerchantID=str(i["supplierDetail"]["wyfMerchantID"]))
            user_data['merchant_id'] = merchant.id
    except:
        pass
    try:
        instance, create = Goods.objects.get_or_create(id=goods_id, defaults=user_data)
        print(instance.id)
        if i['supplyOrgID']:
            level = Level.objects.filter(orgId=i['supplyOrgID'][0]).first()
            if not level:
                level = merchant.level
        else:
            level = merchant.level
        launchedgoods_data = {
            'name': instance.name,
            'caption': instance.caption,
            'goods_id': instance.id,
            'category_id': 1,
            'point': instance.point,
            'price': instance.price,
            'is_launched': 0,
            'level_id': level.id,
            'create_time': instance.create_time
        }
        launchedgoods, create = LaunchedGoods.objects.get_or_create(
            defaults=launchedgoods_data,
            goods_id=instance.id,
            level_id=level.id
        )
        GoodsImage.objects.create(
            goods=instance,
            image=instance.default_image
        )
        return launchedgoods
    except Exception as e:
        print(e)
        print(i['name'])


def pull_userMobile(orderNum):
    method = 'OrderList'
    body = {"page":"1","pageSize":"10","orderNum":orderNum,"specialType":"DIRECT"}
    # print(get_result(method, body))
    result = json.loads(get_result(method, body))['data']['list'][0]
    return result['userMobile']


def pull_user(userMobile):
    # print('%s: pull_ri_user' % time.ctime())
    method = 'MemberList'
    body = {"page": '1', 'pageSize': '1', 'Mobile': userMobile}
    # print(get_result(method, body))
    result = json.loads(get_result(method, body))['data']['list'][0]
    user_data = {}
    # user_data['user_id'] = i['Id']
    user_data['mobile'] = userMobile.replace('+', '')
    user_data['old_openid'] = result['Openid']
    user_data['is_distributor'] = result['isDistributor']
    user_data['idcode'] = result['idcode']
    user_data['realname'] = result['realname']
    user_data['username'] = result['nickname']
    user_data['address'] = result['address']
    user_data['is_offline'] = result['offlineMember']
    user_data['point'] = result['localpoint']
    user_data['avatar'] = result['avatar']
    user_data['create_time'] = result['CreatedAt'].replace('T', ' ').replace('+08:00', '')
    instance, create = CustomerUser.objects.update_or_create(mobile=user_data['mobile'], defaults=user_data)
    return instance


def pull_orderinfo(orderNum):
    # print('%s: pull_ri_order_info' % time.ctime())
    method = 'SaleList'
    body = {"page":"1","pageSize":"10","orderNum":orderNum,"specialType":"DIRECT"}
    return json.loads(get_result(method, body))['data']['list']


def pull_orderinfo1(orderNum):
    # print('%s: pull_ri_order_info' % time.ctime())
    method = 'OrderList'
    body = {"page":"1","pageSize":"10","orderNum":orderNum,"specialType":"DIRECT"}
    return json.loads(get_result(method, body))['data']['list']


def get_ylx_logincode():
    method = 'StaffLoginQrcode'
    body = {"symbol":"gzyz","page":"packages/other/pcLogin/index","width":"600"}
    result = json.loads(post_result(method, body))
    print(result)
    return result


def pull_StaffQrcodeLogin(no):
    print('%s: pull_StaffQrcodeLogin' % time.ctime())
    method = 'StaffQrcodeLogin'
    body = {"no":no, "method":"login"}
    print(login_qrcode_result(method, body))


def staff_qrcode_status(no):
    method = 'StaffQrcodeStatus'
    body = {"no":no}
    result = json.loads(get_result(method, body))
    print(result)
    return result


def synchronization_kl_merchant(start, end, business_no1):
    print('%s: synchronization_kl_order' % time.ctime())
    print(f'{start}至{end}')
    subsidy_url = 'https://manage.gdwxyf.com/internal/searchsubsidydetail.do'
    subsidy_body = {
        "account": 'gdyouzheng',
        "start": start,
        "end": end
    }
    if business_no1:
        subsidy_body['shopId'] = business_no1
    subsidy_response = requests.post(url=subsidy_url, data=subsidy_body)
    subsidy_result = subsidy_response.json()['showList']
    for subsidy in subsidy_result:
        try:
            business_no = subsidy['shopId']
            merchant = Merchant.objects.filter(wyfMerchantID=business_no).first()
            md5 = hashlib.md5()
            md5.update(str(business_no).encode('utf-8'))
            sign = md5.hexdigest()
            if not merchant:
                url = 'https://manage.gdwxyf.com/internal/searchmerchantbyshopids.do'
                body = {
                    'account': 'gdyouzheng',
                    'shopId': sign
                }
                reaponse = requests.post(url=url, data=body)
                try:
                    reaponse = reaponse.json()
                except:
                    return '获取商户信息失败'
                if 'wx_channel_merchant_id' not in reaponse:
                    return '获取商户信息失败'
                # if reaponse['wx_channel_merchant_id'] == '':
                #     return '获取商户信息失败'
                with transaction.atomic():
                    # 创建事务保存点
                    save_id = transaction.savepoint()
                    try:
                        merchant_data = {}
                        channel_mch_id = reaponse['channel_mch_id']
                        channel = Channel.objects.filter(mchid=channel_mch_id).first()
                        if channel:
                            merchant_data['channel_id'] = channel.id
                        merchant_data['name'] = reaponse['shopName']
                        merchant_data['short_name'] = reaponse['shopNickname']
                        merchant_data['wyfMerchantID'] = business_no
                        merchant_data['ruiyinxinMerchantID'] = sign
                        merchant_data['create_time'] = datetime.datetime.now()
                        if reaponse['businessType'] == '1':
                            merchant_data['subject_type'] = 3
                        elif reaponse['businessType'] == '2':
                            merchant_data['subject_type'] = 2
                        elif reaponse['businessType'] == '3':
                            merchant_data['subject_type'] = 1
                        else:
                            merchant_data['subject_type'] = 4
                        level = Level.objects.filter(acceptId=reaponse['accept_id']).first()
                        if level:
                            merchant_data['level_id'] = level.id
                        merchantuser, create = MerchantUser.objects.get_or_create(mobile=reaponse['phone'], defaults={"mobile": reaponse['phone']})
                        merchant_data['merchantuser_id'] = merchantuser.id
                        merchant_data['account_name'] = reaponse['cardName']
                        merchant_data['account_bank'] = reaponse['bankName']
                        merchant_data['account_number'] = reaponse['card']
                        card_copy = f'youhuiquanyi/{business_no}/card_copy.png'
                        card_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/cardFace.png', key=card_copy)
                        if card_copy_url:
                            merchant_data['card_copy'] = card_copy
                        merchant_data['identification_number'] = reaponse['identity']
                        merchant_data['store_address'] = reaponse['address']
                        store_header_copy = f'youhuiquanyi/{business_no}/store_header_copy.png'
                        store_header_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantHead.png', key=store_header_copy)
                        if store_header_copy_url:
                            merchant_data['store_header_copy'] = store_header_copy
                        merchant, create = Merchant.objects.update_or_create(defaults=merchant_data, wyfMerchantID=business_no)
                        if not merchant.managerName:
                            merchant.managerName = reaponse['keeper']
                        if not merchant.managermobile:
                            merchant.managermobile = reaponse['phone']
                        if not merchant.prov_name:
                            merchant.prov_name = reaponse['province']
                            merchant.city_name = reaponse['city']
                            merchant.district_name = reaponse['area']
                        if not merchant.business_category:
                            merchant.business_category_id = 1
                        if not merchant.store_logo_copy:
                            merchant.store_logo_copy = 'default_merchant_logo.jpg'
                        merchant.save()
                        if create and merchant.channel:
                            store_header_copy = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                            store_header_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantHead.png', key=store_header_copy)
                            if store_header_copy_url:
                                MerchantImage.objects.create(merchant_id=merchant.id, image=store_header_copy)
                            store_indoor_copy = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                            store_indoor_copy_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/otherPhoto3.png', key=store_indoor_copy)
                            if store_indoor_copy_url:
                                MerchantImage.objects.create(merchant_id=merchant.id, image=store_indoor_copy)
                            merchantCheck = f'youhuiquanyi/{business_no}/merchant_image{"%06d" % randint(0, 999999)}.png'
                            merchantCheck_url = sync_img_to_local(f'http://ossmerchant.gdwxyf.com/{sign}/merchantCheck.png', key=merchantCheck)
                            if merchantCheck_url:
                                MerchantImage.objects.create(merchant_id=merchant.id, image=merchantCheck)
                        merchantchannel_data = {
                            'merchant_id': merchant.id
                        }
                        if reaponse['allchannelJson']['channel_ruiyinxin']:
                            if reaponse['allchannelJson']['channel_ruiyinxin']['status'] == 1:
                                merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_4']
                                merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_7']
                                merchantchannel_data['channel_id'] = 2
                                merchantchannel_data['sub_mchid'] = reaponse['allchannelJson']['channel_ruiyinxin']['merchant_other_3']
                                MerchantChannel.objects.get_or_create(defaults=merchantchannel_data,
                                                                      merchant_id=merchant.id,
                                                                      channel_id=merchantchannel_data['channel_id'])
                        if reaponse['allchannelJson']['channel_sxf_tq']:
                            if reaponse['allchannelJson']['channel_sxf_tq']['status'] == 1:
                                merchantchannel_data['smid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_other_4'] if 'merchant_other_4' in reaponse['allchannelJson']['channel_sxf_tq'] else ''
                                merchantchannel_data['channel_mchid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_no']
                                merchantchannel_data['channel_id'] = 3
                                merchantchannel_data['sub_mchid'] = reaponse['allchannelJson']['channel_sxf_tq']['merchant_other_3'] if 'merchant_other_3' in reaponse['allchannelJson']['channel_sxf_tq'] else ''
                                MerchantChannel.objects.get_or_create(defaults=merchantchannel_data,
                                                                      merchant_id=merchant.id,
                                                                      channel_id=merchantchannel_data['channel_id'])
                        transaction.savepoint_commit(save_id)
                    except Exception as e:
                        print(e)
                        return '获取商户信息失败'
            order_data = {}
            if 'vm' not in subsidy['shop_order_id']:
                continue
            # check_order = OrderInfo.objects.filter(orderNum=subsidy['shop_order_id'])
            # if check_order:
            #     continue
            order_result = pull_orderinfo(subsidy['shop_order_id'])
            if order_result:
                order_result = order_result[0]
                # check_order = OrderInfo.objects.filter(orderNum=subsidy['shop_order_id']).first()
                # if check_order:
                #     check_mobile = check_order.customer_user.mobile
                #     if check_mobile != order_result['userMobile']:
                #         riuser = CustomerUser.objects.filter(mobile=order_result['userMobile']).first()
                #         if riuser:
                #             check_order.customer_user_id = riuser.id
                #             check_order.save()
                #         else:
                #             riuser = pull_user(order_result['mobile'])
                #             riuser = CustomerUser.objects.get(id=riuser.id)
                #             check_order.customer_user_id = riuser.id
                #             check_order.save()
                #         print(f'更新{check_order.id}')
                #     continue
            else:
                print(subsidy['shop_order_id'])
                continue
            order_data['orderNum'] = order_result['orderNum']
            order_data['order_id'] = order_result['orderNum']
            order_data['create_time'] = order_result['createdAt'].replace('T', ' ').replace('+08:00', '')
            order_data['state'] = 3
            order_data['platform'] = 1
            goods_id = int(order_result['goodsId']) + 10000000
            try:
                launchedgoods = LaunchedGoods.objects.filter(goods_id=goods_id).first()
                if not launchedgoods:
                    launchedgoods = pull_goods(order_result['goodsId'], subsidy['shopId'])
                rimerchant = launchedgoods.goods.merchant
                if rimerchant:
                    order_data['merchant_id'] = merchant.id
            except:
                pass
            try:
                userMobile = pull_userMobile(order_result['orderNum'])
                riuser = CustomerUser.objects.filter(mobile=userMobile).first()
                if riuser:
                    order_data['customer_user_id'] = riuser.id
                else:
                    riuser = pull_user(order_result['mobile'])
                    riuser = CustomerUser.objects.get(id=riuser.id)
                    order_data['customer_user_id'] = riuser.id
            except:
                pass
            order_data['total_point'] = Decimal(order_result['allLocalPoint'])
            order_data['total_price'] = Decimal(order_result['allLocalPoint']) / 100
            order_data['payable_settled_amount'] = Decimal(order_result['allLocalPoint']) / 100
            order_data['total_count'] = order_result['goodsNum']
            order_data['payment_time'] = order_result['createdAt'].replace('T', ' ').replace('+08:00', '')
            order_data['use_time'] = order_result['writeoffAt'].replace('T', ' ').replace('+08:00', '')
            order_data['level_id'] = launchedgoods.level_id
            order_data['bill_order_id'] = subsidy['order_id']
            try:
                instance, create = OrderInfo.objects.update_or_create(orderNum=order_data['orderNum'], defaults=order_data)
                if create:
                    print(instance.id)
                    ordergoods = OrderGoods.objects.create(
                        order=instance,
                        launched_goods=launchedgoods,
                        count=order_result['goodsNum'],
                        price=launchedgoods.goods.price,
                        point=launchedgoods.goods.point,
                        goods_id=launchedgoods.goods_id,
                        merchant_id=launchedgoods.goods.merchant_id
                    )
                    coupons_id = '%06d' % randint(0, 999999) + '%06d' % randint(0, 999999) + '%04d' % randint(0, 999999)
                    GoodsCoupons.objects.create(
                        coupons_id=coupons_id,
                        status=2,
                        goods_id=ordergoods.goods_id,
                        order_id=instance.id,
                        validity_time=datetime.datetime.now(),
                        use_time=order_result['writeoffAt'].replace('T', ' ').replace('+08:00', '')
                    )
                    receipts_time = subsidy['insert_time'][:10]
                    bill = MerchantBill.objects.filter(receipts_time=receipts_time,
                                                       merchant_id=ordergoods.merchant_id).first()
                    if not bill:
                        bill_data = {}
                        bill_data['merchant_id'] = ordergoods.merchant_id
                        bill_data['receipts_time'] = receipts_time
                        bill_data['point'] = instance.total_point
                        bill_data['amount'] = 0
                        bill_data['payable_amount'] = instance.payable_settled_amount
                        bill_data['level_id'] = instance.level_id
                        bill, create = MerchantBill.objects.get_or_create(defaults=bill_data,
                                                                          receipts_time=receipts_time,
                                                                          merchant_id=ordergoods.merchant_id)
                    else:
                        bill.point = bill.point + instance.total_point
                        bill.payable_amount = bill.payable_amount + instance.payable_settled_amount
                        bill.save()
                    instance.bill_id = bill.id
                    instance.save()
                    # instance = OrderInfo.objects.get(id=instance.id)
                    # riuser.point -= instance.point
                    # riuser.save()
                    # PointRecord.objects.create(
                    #     customer_user_id=riuser.id,
                    #     create_time=instance.create_time,
                    #     operate_type=2,
                    #     business_type=2,
                    #     point=instance.point,
                    #     point_balance=riuser.point,
                    #     order_id=instance.id
                    # )
                # else:
                #     is_break = 1
                #     break
            except Exception as e:
                print(e)
                print(order_result['context'])
        except Exception as e:
            print(e)
            pass


def synchronization_kl_order(start, end, shopId=None):
    print('%s: synchronization_kl_order' % time.ctime())
    print(f'{start}至{end}')
    subsidy_url = 'https://manage.gdwxyf.com/internal/searchsubsidydetail.do'
    subsidy_body = {
        "account": 'gdyouzheng',
        "start": start,
        "end": end
    }
    if shopId:
        subsidy_body['shopId'] = shopId
    subsidy_response = requests.post(url=subsidy_url, data=subsidy_body)
    subsidy_result = subsidy_response.json()['showList']
    business_no_list = []
    for subsidy in subsidy_result:
        business_no = subsidy['shopId']
        if business_no not in business_no_list:
            synchronization_kl_merchant(start, end, subsidy['shopId'])
            business_no_list.append(business_no)


def syn_tool():
    a = 0
    start_time = (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d 00:00:00")
    b = 8
    # start_time = '2022-12-22 00:00:00'
    while True:
        if a == b:
            break
        end_time = (datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(hours=3)).strftime("%Y-%m-%d %H:%M:%S")
        synchronization_kl_order(start_time, end_time)
        start_time = end_time
        a += 1
    return '结束'


def wash_customer_mobile():
    customeruser_set = CustomerUser.objects.filter(mobile__contains='***')
    for customeruser in customeruser_set:
        order = OrderInfo.objects.filter(customer_user_id=customeruser.id).first()
        if order:
            orderNum = order.orderNum
            order_result = pull_orderinfo(orderNum)
            mobile = order_result[0]['userMobile']
            try:
                customeruser.mobile = mobile
                customeruser.save()
                print(customeruser.id)
            except Exception as e:
                print(e)
                print(f'{customeruser.id}失败')
        else:
            print(f'{customeruser.id}无订单')


def delete_order():
    queryset = OrderInfo.objects.filter(id__in=[])
    for query in queryset:
        bill = query.bill
        bill.point = bill.point - query.total_point
        bill.payable_amount = bill.payable_amount - query.payable_settled_amount
        bill.save()
        query.delete()


def write_excel_xlsx(path, sheet_name, value):
    index = len(value)
    workbook = openpyxl.Workbook()
    sheet = workbook.active
    sheet.title = sheet_name
    for i in range(0, index):
        for j in range(0, len(value[i])):
            sheet.cell(row=i + 1, column=j + 1, value=str(value[i][j]))
    workbook.save(path)
    print("xlsx格式表格写入数据成功！")


def sms_email(book_name, book_name_xlsx, book):
    my_sender = 'wyh-yunying@wpost.cn'
    my_pass = 'NKuAdwmFm3tsAvZb'
    my_user = 'jiesuan@ruipaycloud.com'
    # my_user = '992294725@qq.com'
    my_cs = '992294725@qq.com,389112780@qq.com,657891648@qq.com'
    con = smtplib.SMTP_SSL('smtphz.qiye.163.com', 465)
    con.login(my_sender, my_pass)
    msg = MIMEMultipart()
    subject = Header('邮米清分结算记录', 'utf-8').encode()
    msg['Subject'] = subject
    msg['From'] = my_sender
    msg['To'] = my_user
    msg['Cc'] = my_cs
    # 添加⽂文字内容
    text = MIMEText(book, 'plain', 'utf-8')
    msg.attach(text)
    # 添加⽂文件附件
    file = MIMEText(open(book_name_xlsx, 'rb').read(), 'base64', 'utf-8')
    file["Content-Disposition"] = "attachment; filename*=utf-8''{}".format(escape_uri_path(book_name))
    msg.attach(file)
    # 发送邮件
    con.sendmail(my_sender, [my_user, '992294725@qq.com', '389112780@qq.com', '657891648@qq.com'], msg.as_string())
    con.quit()


def settlement_order():
    print('%s: settlement_order' % time.ctime())
    today = datetime.datetime.now()
    receipts_time = today.strftime('%Y-%m-%d')
    weeks = today.weekday()
    merchantbillpushdate = MerchantBillPushDate.objects.filter(push_date=receipts_time).first()
    if not merchantbillpushdate:
        return f'星期{weeks + 1}不推送'
    if merchantbillpushdate.is_push == 0:
        return f'节假日不推送'
    count = merchantbillpushdate.count
    # if weeks in [4, 5]:
    #     return f'星期{weeks+1}不推送'
    # if weeks in [6]:
    #     count = 3
    # else:
    #     count = 1
    queryset = OrderInfo.objects.filter(settlement_state=1)
    id_list = list(queryset.values_list('id', flat=True))
    OrderInfo.objects.filter(id__in=id_list).update(settlement_state=6)
    queryset = OrderInfo.objects.filter(id__in=id_list)
    for query in queryset:
        # query = OrderInfo.objects.get(id=query.id)
        # if query.settlement_state != 1:
        #     continue
        sy_order = query.syorderinfo
        if sy_order.money != query.payable_settled_amount:
            query.settlement_state = 3
            query.bill_error_msg = '补贴金额与订单金额不符'
            query.save()
            continue
        merchant = query.merchant
        channel_id = merchant.subsidy_channel_id
        if channel_id == 2:
            channel = 'ruiyinxin'
            re_channel = 'sxf_tq'
            re_channel_id = 3
            query.settlement_state = 3
            query.bill_error_msg = '瑞银信通道不推送'
            query.save()
            continue
        else:
            channel = 'sxf_tq'
            re_channel = 'ruiyinxin'
            re_channel_id = 2
        settlement_amount = merchant.settlement_amount_by_day * count
        merchant_bill = MerchantBill.objects.filter(receipts_time=receipts_time, merchant_id=merchant.id).aggregate(Sum('payable_amount'))
        if merchant_bill['payable_amount__sum']:
            bill_settlement_amount = Decimal(merchant_bill['payable_amount__sum'])
        else:
            bill_settlement_amount = Decimal('0')
        if (bill_settlement_amount + sy_order.money) > settlement_amount:
            query.settlement_state = 1
            query.bill_error_msg = '超过当日补贴金额'
            query.save()
            continue
        body = {
            "shop_id": sy_order.shop_id,
            "shop_order_id": sy_order.shop_order_id,
            "source": 'wx',
            "money": str(sy_order.money),
            "context": sy_order.context,
            "channel": channel
        }
        try:
            if body['channel'] == 'ruiyinxin':
                ruiyinxin_settlement_amount = MerchantBill.objects.filter(receipts_time=receipts_time, channel_id=2, bill_type__in=[1, 3]).aggregate(Sum('payable_amount'))
                if ruiyinxin_settlement_amount['payable_amount__sum']:
                    ruiyinxin_bill_settlement_amount = Decimal(ruiyinxin_settlement_amount['payable_amount__sum'])
                else:
                    ruiyinxin_bill_settlement_amount = Decimal('0')
                if (ruiyinxin_bill_settlement_amount + sy_order.money) > (Decimal(100000) * count):
                    query.bill_error_msg = '瑞银信补贴超过当日补贴金额'
                    query.settlement_state = 3
                    query.save()
                    continue
            result = ryx_settle_order_wx(body)
            if result['result_code'] == 'success':
                if not query.bill_id:
                    bill = MerchantBill.objects.filter(receipts_time=receipts_time, merchant_id=merchant.id, channel_id=channel_id, bill_type=query.order_species).first()
                    if not bill:
                        bill_data = {}
                        bill_data['merchant_id'] = merchant.id
                        bill_data['receipts_time'] = receipts_time
                        bill_data['point'] = query.total_point
                        bill_data['amount'] = 0
                        bill_data['payable_amount'] = sy_order.money
                        bill_data['level_id'] = query.level_id
                        bill_data['channel_id'] = channel_id
                        bill_data['bill_type'] = query.order_species
                        bill, create = MerchantBill.objects.get_or_create(defaults=bill_data, receipts_time=receipts_time, merchant_id=merchant.id, channel_id=channel_id, bill_type=query.order_species)
                    else:
                        bill.point = bill.point + query.total_point
                        bill.payable_amount = bill.payable_amount + sy_order.money
                        bill.save()
                    query.bill_order_id = result['order_id']
                    query.save()
                    query.bill_id = bill.id
                    query.settlement_state = 2
                    query.success_time = datetime.datetime.now()
                    query.bill_error_msg = None
                    query.save()
                else:
                    query.bill_order_id = result['order_id']
                    query.settlement_state = 2
                    query.success_time = datetime.datetime.now()
                    query.bill_error_msg = None
                    query.save()
            else:
                # if result['error_msg'] == '当前商户未开通此补贴渠道，请确认':
                #     merchant.subsidy_channel_id = re_channel_id
                #     merchant.save()
                #     body = {
                #         "shop_id": sy_order.shop_id,
                #         "shop_order_id": sy_order.shop_order_id,
                #         "source": 'wx',
                #         "money": str(sy_order.money),
                #         "context": sy_order.context,
                #         "channel": re_channel
                #     }
                #     if body['channel'] == 'ruiyinxin':
                #         ruiyinxin_settlement_amount = MerchantBill.objects.filter(receipts_time=receipts_time, channel_id=2).aggregate(Sum('payable_amount'))
                #         if ruiyinxin_settlement_amount['payable_amount__sum']:
                #             ruiyinxin_bill_settlement_amount = Decimal(ruiyinxin_settlement_amount['payable_amount__sum'])
                #         else:
                #             ruiyinxin_bill_settlement_amount = Decimal('0')
                #         if (ruiyinxin_bill_settlement_amount + sy_order.money) > (Decimal(100000) * count):
                #             query.bill_error_msg = '瑞银信补贴超过当日补贴金额'
                #             query.settlement_state = 3
                #             query.save()
                #             continue
                #     result = ryx_settle_order_wx(body)
                #     if result['result_code'] == 'success':
                #         bill = MerchantBill.objects.filter(receipts_time=receipts_time, merchant_id=merchant.id, channel_id=re_channel_id, bill_type=query.order_species).first()
                #         if not bill:
                #             bill_data = {}
                #             bill_data['merchant_id'] = merchant.id
                #             bill_data['receipts_time'] = receipts_time
                #             bill_data['point'] = query.total_point
                #             bill_data['amount'] = 0
                #             bill_data['payable_amount'] = sy_order.money
                #             bill_data['level_id'] = query.level_id
                #             bill_data['channel_id'] = re_channel_id
                #             bill_data['bill_type'] = query.order_species
                #             bill, create = MerchantBill.objects.get_or_create(defaults=bill_data, receipts_time=receipts_time, merchant_id=merchant.id, channel_id=re_channel_id, bill_type=query.order_species)
                #         else:
                #             bill.point = bill.point + query.total_point
                #             bill.payable_amount = bill.payable_amount + sy_order.money
                #             bill.save()
                #         query.bill_order_id = result['order_id']
                #         query.save()
                #         query.bill_id = bill.id
                #         query.settlement_state = 2
                #         query.success_time = datetime.datetime.now()
                #         query.bill_error_msg = None
                #         query.save()
                #     else:
                #         query.bill_id = None
                #         query.settlement_state = 3
                #         query.success_time = None
                #         query.bill_error_msg = result['error_msg']
                #         query.save()
                # else:
                # query.bill_id = None
                query.settlement_state = 3
                query.success_time = None
                query.bill_error_msg = result['error_msg']
                query.save()
        except Exception as e:
            print(e)
            # query.bill_id = None
            query.settlement_state = 3
            query.success_time = None
            query.bill_error_msg = '推送失败'
            query.save()
    print(len(queryset))


def cancel_order1():
    query_set = OrderInfo.objects.filter(id__in=[4301533,4301536,4301546,4301549,4301551,4301561,4301563,4301568,4301577,4301580,4301591,4301596,4301607,4301612,4301620,4301625,4301631,4301637,4301639,4301641,4301646,4301659,4301665,4301666,4301669,4301696,4301702,4301707,4301732,4301734,4301740,4301748,4301749,4301754,4301758,4301762,4301769,4301770,4301774,4301778,4301797,4301798,4301806,4301811,4301814,4301818,4301822,4301824,4301829,4301831,4301837,4301843,4301868,4301871,4301872,4301877,4301882,4301884,4301886,4301889,4301890,4301904,4301913,4301917,4301918,4301933,4301945,4301951,4301953,4301954,4301956,4301957,4301963,4301971,4301974,4301985,4301986,4301991,4301996,4302002,4302004,4302005,4302006,4302009,4302010,4302018,4302025,4302028,4302032,4302045,4302056,4302057,4302059,4302060,4302063,4302066,4302072,4302077,4302079,4302084,4302087,4302095,4302098,4302108,4302113,4302120,4302123,4302136,4302141,4302148,4302152,4302162,4302163,4302164,4302165,4302166,4302196,4302211,4302220,4302224,4302229,4302235,4302264,4302269,4302286,4302303,4302324,4302325,4302328,4302338,4302343,4302342,4302348,4302365,4302367,4302395,4302394,4302418,4302423,4302426,4302433,4302434,4302438,4302446,4302467,4302479,4302481,4302482,4302498,4302501,4302521,4302522,4302524,4302538,4302543,4302545,4302550,4302557,4302569,4302575,4302582,4302591,4302598,4302603,4302604,4302605,4302621,4302622,4302628,4302634,4302648,4302664,4302673,4302671,4302676,4302677,4302680,4302692,4302695,4302697,4302706,4302720,4302726,4302753,4302757,4302790,4302808,4302809,4302820,4302844,4302900,4302915,4302920,4302927,4302955,4302971,4302987,4302994,4302999,4303002,4303010,4303012,4303027,4303029,4303033,4303051,4303061,4303069,4303075,4303079,4303087,4303091,4303101,4303113,4303116,4303120,4303136,4303138,4303145,4303147,4303161,4303167,4303184,4303188,4303198,4303202,4303218,4314559,4303237,4314560,4303240,4303241,4303251,4303259,4303264,4314587,4314590,4314592,4314593,4314595,4314598,4314600,4314605,4303291,4303295,4303301,4303313,4303326,4303334,4303343,4303355,4303394,4303401,4303414,4303426,4303430,4303439,4303441,4303443,4303444,4303450,4303467,4303470,4303480,4303481,4303483,4303494,4303496,4303500,4303511,4303516,4303517,4303518,4303523,4303531,4303536,4303537,4303543,4303545,4303559,4303572,4303573,4303580,4303587,4303588,4303595,4303597,4303600,4303601,4303605,4303608,4303614,4303615,4303619,4303620,4303631,4303635,4303641,4303642,4314610,4314613,4303668,4303670,4314640,4314647,4303687,4303689,4303692,4303709,4303721,4303729,4303739,4303747,4303752,4303753,4303757,4303781,4303790,4303792,4303800,4303799,4303803,4303812,4303813,4303820,4303829,4303845,4303860,4303861,4303863,4303867,4303871,4303887,4303888,4303891,4303901,4303912,4303914,4303919,4303937,4303954,4303962,4303970,4303975,4303981,4303995,4303997,4304006,4304018,4304029,4304038,4304039,4304049,4304052,4304062,4304066,4304070,4304071,4304078,4304080,4304086,4304091,4304093,4304118,4304119,4304125,4304129,4304133,4304139,4304145,4304146,4304148,4304157,4304159,4304176,4304177,4304179,4304191,4304193,4304195,4304196,4304205,4304207,4304239,4304242,4304243,4304258,4304259,4304268,4304270,4304277,4304280,4304281,4304283,4304292,4304293,4304295,4304299,4304300,4304304,4304307,4304313,4304321,4304333,4304334,4304342,4304347,4304355,4304377,4304384,4304387,4304398,4304400,4304402,4304404,4304412,4304428,4304437,4304440,4304441,4304443,4304456,4304460,4304473,4304476,4304480,4304483,4304487,4304488,4304490,4304496,4304500,4304517,4304527,4304543,4304562,4304571,4304574,4304588,4304591,4304598,4304605,4304606,4304612,4304614,4304641,4304642,4304660,4304661,4304667,4304675,4304677,4304685,4304686,4304693,4304696,4304698,4304704,4304712,4304729,4304739,4304743,4304761,4304766,4304767,4304777,4304780,4304782,4304797,4304807,4304821,4304825,4304831,4304840,4304847,4304848,4304856,4304860,4304861,4304869,4304876,4304877,4304878,4304885,4304886,4304889,4304901,4304902,4304941,4304947,4304952,4304954,4304956,4304959,4304966,4304972,4304980,4304981,4304983,4304984,4304985,4304987,4304990,4304995,4305007,4305018,4305032,4305051,4305060,4305064,4305068,4305072,4305073,4305081,4305088,4305095,4305105,4305112,4305131,4305133,4305135,4305155,4305173,4305189,4305202,4305203,4305210,4305212,4305215,4305218,4305220,4305226,4305232,4305238,4305242,4305243,4305255,4305258,4305265,4305267,4305274,4305306,4305311,4305319,4305353,4305355,4305357,4305361,4305364,4305365,4305374,4305377,4305409,4305412,4305429,4305435,4305445,4305446,4305456,4305469,4305470,4305471,4305473,4305479,4305478,4305483,4305492,4305500,4305504,4305506,4305508,4305511,4305516,4305533,4305536,4305541,4305543,4305544,4305550,4305557,4305564,4305571,4305584,4305593,4305597,4305616,4305627,4305643,4305649,4305651,4305655,4305659,4305661,4305665,4305666,4305670,4305673,4305698,4305705,4305708,4305723,4305726,4305728,4305737,4305738,4305743,4305749,4305767,4305778,4305796,4305803,4305812,4305818,4305825,4305839,4305841,4305843,4305857,4305869,4305877,4305878,4305885,4305890,4305894,4305912,4305920,4305922,4305931,4305990,4306002,4306006,4306027,4306031,4306035,4306067,4306081,4306086,4306091,4306107,4306112,4306113,4306126,4306138,4306140,4306172,4306187,4306189,4306190,4306198,4306199,4306205,4306219,4306221,4306228,4306229,4306231,4306245,4306254,4306256,4306261,4306274,4306319,4306338,4306341,4306357,4306379,4306389,4306399,4306401,4306406,4306408,4306413,4306414,4306418,4306425,4306435,4306449,4306457,4306465,4306466,4306474,4306475,4306485,4306495,4306506,4306507,4306508,4306516,4306518,4306522,4306539,4306541,4306543,4306549,4306553,4306554,4306555,4306564,4306570,4306574,4306575,4306593,4306599,4306602,4306605,4306609,4306611,4306612,4306628,4306630,4306631,4306636,4306638,4306649,4306676,4306675,4306684,4306688,4306699,4306701,4306703,4306708,4306710,4306724,4306728,4306729,4306730,4306733,4306737,4306743,4306746,4306750,4306753,4306755,4306763,4306768,4306777,4306779,4306780,4306785,4306786,4306798,4306808,4306813,4306819,4306828,4306836,4306845,4306854,4306855,4306863,4306866,4306868,4306873,4306877,4306878,4306880,4306884,4306898,4306899,4306909,4306911,4306912,4306924,4306928,4306934,4306935,4306939,4306942,4306958,4306967,4306968,4306970,4306986,4306996,4307011,4307014,4307018,4307019,4307026,4307036,4307039,4307044,4307049,4307050,4307059,4307060,4307069,4307070,4307074,4307080,4307085,4307087,4307090,4307097,4307105,4307113,4307131,4307140,4307161,4307164,4307167,4307170,4307187,4307190,4307204,4307206,4307221,4307252,4307258,4307266,4307269,4307272,4307283,4307296,4307311,4307315,4307323,4307355,4307364,4307366,4307368,4307376,4307381,4307383,4307384,4307386,4307387,4307388,4307389,4307391,4307392,4307393,4307397,4307398,4307406,4307413,4307415,4307426,4307434,4307438,4307443,4307476,4307477,4307481,4307489,4307492,4307500,4307501,4307504,4307507,4307515,4307516,4307520,4307523,4307526,4307530,4307531,4307532,4307538,4307548,4307561,4307567,4307588,4307590,4307593,4307600,4307606,4307624,4307626,4307632,4307637,4307639,4307640,4307646,4307649,4307653,4307656,4307660,4307664,4307666,4307676,4307678,4307689,4307697,4307706,4307707,4307719,4307721,4307725,4307732,4307737,4307756,4307771,4307786,4307798,4307807,4307808,4307817,4307820,4307827,4307845,4307852,4307855,4307860,4307861,4307863,4307867,4307874,4307886,4307887,4307902,4307917,4307926,4307932,4307934,4307936,4307945,4307948,4307953,4307957,4307970,4307976,4307986,4307990,4307992,4307994,4308003,4308004,4308009,4308010,4308016,4308036,4308039,4308049,4308055,4308056,4308063,4308071,4308087,4308089,4308092,4308098,4308100,4308101,4308106,4308107,4308110,4308111,4308135,4308138,4308143,4308145,4308148,4308153,4308154,4308165,4308168,4308173,4308180,4308182,4308194,4308208,4308227,4308228,4308229,4308230,4308236,4308246,4308254,4308256,4308258,4308263,4308287,4308288,4308296,4308302,4308305,4308307,4308309,4308316,4308318,4308346,4308347,4308351,4308354,4308362,4308365,4308370,4308372,4308383,4308390,4308399,4308401,4308403,4308404,4308408,4308413,4308422,4308430,4308442,4308444,4308446,4308449,4308456,4308465,4308475,4308481,4308482,4308490,4308493,4308499,4308502,4308503,4308506,4308527,4308532,4308538,4308546,4308553,4308554,4308555,4308556,4308558,4308560,4308562,4308563,4308565,4308566,4308567,4308568,4308571,4308575,4308576,4308578,4308583,4308584,4308593,4308594,4308604,4308606,4308607,4308609,4308616,4308623,4308654,4308669,4308670,4308673,4308688,4308696,4308704,4308707,4308710,4308725,4308736,4308742,4308746,4308752,4308753,4308756,4308758,4308764,4308775,4308778,4308793,4308794,4308796,4308800,4308811,4308812,4308825,4308827,4308832,4308837,4308848,4308857,4308860,4308863,4308868,4308872,4308873,4308874,4308886,4308887,4308888,4308899,4308911,4308933,4308936,4308945,4308951,4308953,4308960,4308961,4308970,4308972,4308999,4309024,4309037,4309046,4309049,4309056,4309057,4309063,4309064,4309077,4309081,4309093,4309122,4309130,4309132,4309134,4309136,4309139,4309140,4309150,4309157,4309159,4309165,4309171,4309174,4309185,4309188,4309190,4309192,4309203,4309205,4309209,4309214,4309223,4309226,4309236,4309240,4309246,4309256,4309258,4309266,4309287,4309303,4309305,4309325,4309344,4309348,4309363,4309369,4309367,4309370,4309373,4309372,4309402,4309410,4309420,4309435,4309437,4309444,4309446,4309449,4309453,4309466,4309476,4309484,4309488,4309489,4309499,4309500,4309501,4309523,4309533,4309538,4309539,4309551,4309553,4309563,4309564,4309566,4309569,4309571,4309585,4309586,4309592,4309611,4309615,4309632,4309633,4309635,4309655,4309667,4309668,4309697,4309701,4309719,4309730,4309733,4309739,4309747,4309749,4309766,4309769,4309783,4309786,4309797,4309799,4309811,4309821,4309824,4309828,4309830,4309833,4309835,4309837,4309838,4309842,4309843,4309844,4309846,4309851,4309856,4309857,4309858,4309859,4309872,4309874,4309879,4309884,4309888,4309892,4309893,4309899,4309902,4309905,4309906,4309915,4309916,4309924,4309927,4309931,4309937,4309942,4309946,4309968,4309975,4309978,4309992,4310005,4310032,4310037,4310049,4310064,4310123,4310135,4310140,4310149,4310157,4310165,4310171,4310177,4310181,4310186,4310185,4310187,4310192,4310199,4310201,4310209,4310213,4310216,4310218,4310227,4310230,4310238,4310253,4310254,4310261,4310263,4310264,4310267,4310271,4310280,4310294,4310305,4310309,4310314,4310318,4310340,4310408,4310415,4310422,4310460,4310467,4310473,4310487,4310490,4310492,4310498,4310500,4310501,4310503,4310520,4310521,4310539,4310541,4310547,4310570,4310591,4310600,4310611,4310616,4310617,4310626,4310631,4310633,4310637,4310647,4310666,4310671,4310689,4310699,4310702,4310706,4310708,4310726,4310729,4310740,4310749,4310760,4310762,4310765,4310774,4310780,4310781,4310787,4310791,4310793,4310803,4310811,4310813,4310819,4310832,4310834,4310841,4310844,4310848,4310849,4310850,4310855,4310858,4310865,4310870,4310873,4310877,4310886,4310892,4310911,4310912,4310913,4310920,4310927,4310933,4310934,4310957,4310966,4310981,4310982,4310983,4310984,4310987,4310998,4311009,4311010,4311025,4311026,4311037,4311038,4311062,4311071,4311076,4311077,4311085,4311108,4311110,4311114,4311116,4311130,4311136,4311142,4311148,4311149,4311152,4311157,4311159,4311162,4311183,4311190,4311197,4311200,4311212,4311253,4311264,4311279,4311289,4311322,4311332,4311344,4311349,4311377,4311383,4311408,4311418,4311425,4311431,4311433,4311435,4311440,4311448,4311458,4311463,4311464,4311471,4311473,4311491,4311498,4311504,4311522,4311536,4311538,4311545,4311547,4311554,4311565,4311568,4311575,4311576,4311579,4311578,4311583,4311590,4311591,4311598,4311603,4311612,4311622,4311628,4311629,4311638,4311647,4311648,4311652,4311663,4311671,4311681,4311691,4311693,4311697,4311715,4311719,4311721,4311751,4311766,4311768,4311787,4311797,4311796,4311809,4311810,4311818,4311822,4311842,4311844,4311845,4311852,4311853,4311854,4311857,4311882,4311888,4311894,4311895,4311896,4311898,4311906,4311909,4311910,4311911,4311912,4311919,4311928,4311950,4311951,4311956,4311966,4311967,4311973,4311974,4311978,4311979,4311984,4311986,4311991,4311996,4311997,4312008,4312009,4312025,4312035,4312056,4312062,4312080,4312083,4312096,4312101,4312108,4312116,4312119,4312122,4312123,4312129,4312131,4312139,4312149,4312157,4312166,4312188,4312193,4312194,4312209,4312212,4312216,4312222,4312226,4312227,4312235,4312241,4312242,4312243,4312250,4312252,4312263,4312267,4312270,4312271,4312272,4312275,4312295,4312296,4312302,4312307,4312310,4312314,4312320,4312319,4312342,4312343,4312349,4312353,4312361,4312365,4312379,4312386,4312404,4312412,4312414,4312416,4312421,4312439,4312445,4312454,4312462,4312471,4312473,4312476,4312486,4312501,4312504,4312506,4312525,4312536,4312537,4312544,4312547,4312552,4312554,4312563,4312566,4312571,4312572,4312585,4312589,4312593,4312596,4312602,4312603,4312612,4312617,4312620,4312628,4312629,4312632,4312640,4312642,4312650,4312653,4312656,4312693,4312695,4312713,4312723,4312730,4312743,4312747,4312749,4312783,4312793,4312801,4312802,4312811,4312813,4312837,4312848,4312856,4312872,4312875,4312878,4312885,4312913,4312917,4312932,4312933,4312943,4312951,4312956,4312965,4312968,4312973,4312991,4312992,4312999,4313006,4313011,4313043,4313044,4313049,4313051,4313063,4313065,4313066,4313071,4313082,4313087,4313089,4313091,4313096,4313098,4313107,4313117,4313118,4313126,4313129,4313140,4313147,4313148,4313149,4313162,4313163,4313165,4313171,4313177,4313179,4313180,4313183,4313193,4313214,4313225,4313230,4313243,4313248,4313253,4313280,4313293,4313299,4313303,4313304,4313307,4313311,4313312,4313315,4313321,4313326,4313333,4313348,4313366,4313368,4313380,4313398,4313401,4313402,4313405,4313409,4313431,4313432,4313442,4313443,4313451,4313453,4313458,4313463,4313466,4313474,4313477,4313478,4313479,4313482,4313484,4313511,4313513,4313539,4313541,4313550,4313551,4313562,4313565,4313566,4313567,4313576,4313577,4313579,4313584,4313597,4313602,4313603,4313607,4313634,4313638,4313641,4313650,4313651,4313653,4313654,4313681,4313684,4313687,4313688,4313705,4313734,4313736,4313753,4313763,4313769,4313772,4313800,4313819,4313824,4313825,4313826,4313831,4313851,4313869,4313876,4313890,4313894,4313902,4313903,4313911,4313914,4313924,4313927,4313934,4313945,4313949,4313964,4313967,4313975,4313979,4313980,4313990,4313992,4313996,4313997,4314004,4314005,4314033,4314044,4314052,4314057,4314064,4314068,4314074,4314083,4314105,4314128,4314136,4314138,4314137,4314141,4314145,4314147,4314154,4314162,4314164,4314169,4314177,4314211,4314219,4314234,4314238,4314245,4314248,4314254,4314274,4314275,4314280,4314283,4314287,4314289,4314296,4314310,4314340,4314341,4314346,4314351,4314354,4314357,4314358,4314364,4314374,4314378,4314379,4314382,4314390,4314394,4314402,4314411,4314429,4314430,4314438,4314447,4314453,4314456,4314459,4314467,4314472,4314474,4314491,4314520,4314525,4314529,4314531,4314535,4314542,4314543,4314545,4314572,4314637,4314638,4314670,4314677,4314679,4314682,4314717,4314719,4314738,4314739,4314741,4314755,4314759,4314768,4314773,4314785,4314788,4314793,4314796,4314802,4314806,4314808,4314813,4314815,4314821,4314825,4314830,4314839,4314846,4314847,4314848,4314849,4314850,4314851,4314857,4314867,4314871,4314877,4314881,4314885,4314889,4314893,4314895,4314923,4314935,4314962,4314967,4315000,4315039,4315043,4315056,4315057,4315096,4315099,4315106,4315112,4315115,4315121,4315131,4315158,4315191,4315196,4315200,4315202])
    url = 'https://manage.gdwxyf.com/internal/cannelchannelsubsidyorder.do'
    key = '4C685CEA1B7724760AFE593DE533BB5A'
    for query in query_set:
        sy_order = query.syorderinfo
        shop_order_id = sy_order.shop_order_id
        body = {
            "shop_id": sy_order.shop_id,
            "shop_order_id": shop_order_id,
            "source": "wx"
        }
        params_list = sorted(body.items(), key=lambda e: e[0], reverse=False)  # 参数字典倒排序为列表
        params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list) + '&key=' + key
        # 组织参数字符串并在末尾添加商户交易密钥
        md5 = hashlib.md5()  # 使用MD5加密模式
        md5.update(params_str.encode('utf-8'))  # 将参数字符串传入
        sign = md5.hexdigest().upper()  # 完成加密并转为大写
        print(sign)
        body['sign'] = sign
        response = requests.post(url=url, data=json.dumps(body))
        print(response.json())
        bill = query.bill
        bill.point = bill.point - query.total_point
        bill.payable_amount = bill.payable_amount - sy_order.money
        bill.save()
        query.success_time = None
        query.settlement_state = 3
        query.bill_error_msg = '瑞银信补贴超过当日补贴金额'
        query.save()
        sy_order.shop_order_id = f'{shop_order_id}_1'
        sy_order.save()


def sms_settlement_order_email():
    today = datetime.datetime.now() + datetime.timedelta(days=-1)
    l2 = []
    table_title = ['渠道号', '订单号', '金额', '商户号', '推送状态', '最后推送时间', '失败原因']
    l2.append(table_title)
    success_time__gte = today.strftime('%Y-%m-%d 00:00:00')
    success_time__lte = today.strftime('%Y-%m-%d 23:59:59')
    queryset = OrderInfo.objects.filter(success_time__gte=success_time__gte, success_time__lte=success_time__lte, settlement_state=2)
    if queryset:
        for query in queryset:
            merchant = query.merchant
            table_body = []
            table_body.append('gzyz')
            table_body.append(str(query.orderNum))
            table_body.append(str(query.payable_settled_amount))
            table_body.append(str(merchant.wyfMerchantID))
            table_body.append('推送成功')
            table_body.append(query.success_time.strftime("%Y-%m-%d %H:%M:%S"))
            table_body.append('')
            l2.append(table_body)
        book = f'邮米清分结算记录_{today.strftime("%Y%m%d")}'
        book_name = f'{book}.xlsx'
        book_name_xlsx = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), f'static/{book_name}')
        sheet_name_xlsx = 'Sheet1'
        write_excel_xlsx(book_name_xlsx, sheet_name_xlsx, l2)
        sms_email(book_name, book_name_xlsx, book)


def settlement_residentialhostel_order():
    print('%s: settlement_residentialhostel_order' % time.ctime())
    today = datetime.datetime.now()
    receipts_time = today.strftime('%Y-%m-%d')
    weeks = today.weekday()
    merchantbillpushdate = MerchantBillPushDate.objects.filter(push_date=receipts_time).first()
    if not merchantbillpushdate:
        return f'星期{weeks + 1}不推送'
    if merchantbillpushdate.is_push == 0:
        return f'节假日不推送'
    count = merchantbillpushdate.count
    # today = datetime.datetime.now()
    # weeks = today.weekday()
    # if weeks in [4, 5]:
    #     return f'星期{weeks+1}不推送'
    # if weeks == 6:
    #     count = 3
    # else:
    #     count = 1
    queryset = OrderInfo.objects.filter(settlement_state=4)
    for query in queryset:
        merchant = query.merchant
        channel_id = merchant.subsidy_channel_id
        if channel_id == 2:
            channel = 'ruiyinxin'
            re_channel = 'sxf_tq'
            re_channel_id = 3
            query.bill_error_msg = '瑞银信通道不推送'
            query.save()
            continue
        else:
            channel = 'sxf_tq'
            re_channel = 'ruiyinxin'
            re_channel_id = 2
        merchant_channel = MerchantChannel.objects.filter(merchant_id=merchant.id, channel_id=channel_id).first()
        if merchant_channel:
            is_subsidy = merchant_channel.is_subsidy
            if is_subsidy == 0:
                can_subsidy = check_shop_can_subsidy(merchant.ruiyinxinMerchantID, channel)
                if can_subsidy['is_can_subsidy'] == 2:
                    a = 0
                    while True:
                        if a >= 10:
                            break
                        time.sleep(20)
                        can_subsidy = check_shop_can_subsidy(merchant.ruiyinxinMerchantID, channel)
                        if can_subsidy['is_can_subsidy'] == 1:
                            merchant_channel.is_subsidy = 1
                            merchant_channel.save()
                            break
                        elif can_subsidy['is_can_subsidy'] == 0:
                            merchant_channel.is_subsidy = 2
                            merchant_channel.save()
                            break
                        a += 1
                elif can_subsidy['is_can_subsidy'] == 0:
                    merchant_channel.is_subsidy = 2
                    merchant_channel.save()
                    merchant_channel = MerchantChannel.objects.filter(merchant_id=merchant.id, channel_id=re_channel_id).first()
                    is_subsidy = merchant_channel.is_subsidy
                    if is_subsidy == 0:
                        can_subsidy = check_shop_can_subsidy(merchant.ruiyinxinMerchantID, re_channel)
                        if can_subsidy['is_can_subsidy'] == 2:
                            a = 0
                            while True:
                                if a >= 10:
                                    break
                                time.sleep(20)
                                can_subsidy = check_shop_can_subsidy(merchant.ruiyinxinMerchantID, re_channel)
                                if can_subsidy['is_can_subsidy'] == 1:
                                    merchant_channel.is_subsidy = 1
                                    merchant_channel.save()
                                    break
                                elif can_subsidy['is_can_subsidy'] == 0:
                                    merchant_channel.is_subsidy = 2
                                    merchant_channel.save()
                                    break
                                a += 1
                        elif can_subsidy['is_can_subsidy'] == 0:
                            merchant_channel.is_subsidy = 2
                            merchant_channel.save()
                        elif can_subsidy['is_can_subsidy'] == 1:
                            merchant_channel.is_subsidy = 1
                            merchant_channel.save()
                elif can_subsidy['is_can_subsidy'] == 1:
                    merchant_channel.is_subsidy = 1
                    merchant_channel.save()
        else:
            merchant_channel = MerchantChannel.objects.filter(merchant_id=merchant.id, channel_id=re_channel_id).first()
            is_subsidy = merchant_channel.is_subsidy
            if is_subsidy == 0:
                can_subsidy = check_shop_can_subsidy(merchant.ruiyinxinMerchantID, re_channel)
                if can_subsidy['is_can_subsidy'] == 2:
                    a = 0
                    while True:
                        if a >= 10:
                            break
                        time.sleep(20)
                        can_subsidy = check_shop_can_subsidy(merchant.ruiyinxinMerchantID, re_channel)
                        if can_subsidy['is_can_subsidy'] == 1:
                            merchant_channel.is_subsidy = 1
                            merchant_channel.save()
                            break
                        elif can_subsidy['is_can_subsidy'] == 0:
                            merchant_channel.is_subsidy = 2
                            merchant_channel.save()
                            break
                        a += 1
                elif can_subsidy['is_can_subsidy'] == 0:
                    merchant_channel.is_subsidy = 2
                    merchant_channel.save()
                elif can_subsidy['is_can_subsidy'] == 1:
                    merchant_channel.is_subsidy = 1
                    merchant_channel.save()
        settlement_amount = merchant.settlement_amount_by_day * count
        receipts_time = today.strftime('%Y-%m-%d')
        merchant_bill = MerchantBill.objects.filter(receipts_time=receipts_time, merchant_id=merchant.id).aggregate(Sum('payable_amount'))
        if merchant_bill['payable_amount__sum']:
            bill_settlement_amount = Decimal(merchant_bill['payable_amount__sum'])
        else:
            bill_settlement_amount = Decimal('0')
        if (bill_settlement_amount + query.payable_settled_amount) > settlement_amount:
            query.settlement_state = 4
            query.bill_error_msg = '超过当日补贴金额'
            query.save()
            continue
        body = {
            "shop_id": query.merchant.ruiyinxinMerchantID,
            "shop_order_id": query.orderNum,
            "source": 'wx',
            "money": str(query.payable_settled_amount),
            "context": query.residentialhostelorderinfo.context,
            "channel": channel
        }
        result = ryx_settle_order_wx(body)
        if result['result_code'] == 'success':
            bill = MerchantBill.objects.filter(receipts_time=receipts_time, merchant_id=merchant.id, channel_id=channel_id, bill_type=query.order_species).first()
            if not bill:
                bill_data = {}
                bill_data['merchant_id'] = merchant.id
                bill_data['receipts_time'] = receipts_time
                bill_data['point'] = query.total_point
                bill_data['amount'] = 0
                bill_data['payable_amount'] = query.payable_settled_amount
                bill_data['level_id'] = query.level_id
                bill_data['channel_id'] = channel_id
                bill_data['bill_type'] = query.order_species
                bill, create = MerchantBill.objects.get_or_create(defaults=bill_data, receipts_time=receipts_time, merchant_id=merchant.id, channel_id=channel_id, bill_type=query.order_species)
            else:
                bill.point = bill.point + query.total_point
                bill.payable_amount = bill.payable_amount + query.payable_settled_amount
                bill.save()
            query.bill_id = bill.id
            query.settlement_state = 2
            query.success_time = datetime.datetime.now()
            query.bill_order_id = result['order_id']
            query.save()
        else:
            if result['error_msg'] == '当前商户未开通此补贴渠道，请确认':
                merchant.subsidy_channel_id = re_channel_id
                merchant.save()
                body = {
                    "shop_id": query.merchant.ruiyinxinMerchantID,
                    "shop_order_id": query.orderNum,
                    "source": 'wx',
                    "money": str(query.payable_settled_amount),
                    "context": query.residentialhostelorderinfo.context,
                    "channel": re_channel
                }
                result = ryx_settle_order_wx(body)
                if result['result_code'] == 'success':
                    bill = MerchantBill.objects.filter(receipts_time=receipts_time, merchant_id=merchant.id, channel_id=re_channel_id, bill_type=query.order_species).first()
                    if not bill:
                        bill_data = {}
                        bill_data['merchant_id'] = merchant.id
                        bill_data['receipts_time'] = receipts_time
                        bill_data['point'] = query.total_point
                        bill_data['amount'] = 0
                        bill_data['payable_amount'] = query.payable_settled_amount
                        bill_data['level_id'] = query.level_id
                        bill_data['channel_id'] = re_channel_id
                        bill_data['bill_type'] = query.order_species
                        bill, create = MerchantBill.objects.get_or_create(defaults=bill_data, receipts_time=receipts_time, merchant_id=merchant.id, channel_id=re_channel_id, bill_type=query.order_species)
                    else:
                        bill.point = bill.point + query.total_point
                        bill.payable_amount = bill.payable_amount + query.payable_settled_amount
                        bill.save()
                    query.bill_id = bill.id
                    query.settlement_state = 2
                    query.success_time = datetime.datetime.now()
                    query.bill_order_id = result['order_id']
                    query.save()
                else:
                    query.settlement_state = 3
                    query.bill_error_msg = result['error_msg']
                    query.save()
            else:
                query.settlement_state = 3
                query.bill_error_msg = result['error_msg']
                query.save()
    print(len(queryset))


def delete_bill_order_id():
    queryset = OrderInfo.objects.filter(id__in=[])
    for query in queryset:
        bill = query.bill
        bill.point = bill.point - query.total_point
        bill.payable_amount = bill.payable_amount - query.payable_settled_amount
        bill.save()
        query.settlement_state = 1
        query.success_time = None
        query.bill_id = None
        query.save()


def query_order_bill():
    queryset = OrderInfo.objects.filter(id__in=[3530882,3528774,3522928,3531109,3520775,3535067,3537041,3529916,3521035,3521469,3521780,3522263,3522622,3522723,3524445,3523419,3523904,3523594,3523863,3523901,3524914,3525041,3525477,3538802,3525449,3539581,3539749,3526435,3526900,3527286,3527761,3528576,3528561,3529822,3530328,3530514,3530582,3532883,3534822,3534640,3534709,3535307,3535743,3536010,3536093,3537367,3540612])
    for query in queryset:
        merchant = query.merchant
        receipts_time = '2023-08-01'
        bill = MerchantBill.objects.filter(receipts_time=receipts_time, merchant_id=merchant.id, channel_id=3).first()
        if not bill:
            bill_data = {}
            bill_data['merchant_id'] = merchant.id
            bill_data['receipts_time'] = receipts_time
            bill_data['point'] = query.total_point
            bill_data['amount'] = 0
            bill_data['payable_amount'] = query.payable_settled_amount
            bill_data['level_id'] = query.level_id
            bill_data['channel_id'] = 3
            bill, create = MerchantBill.objects.get_or_create(defaults=bill_data, receipts_time=receipts_time, merchant_id=merchant.id, channel_id=3)
        else:
            bill.point = bill.point + query.total_point
            bill.payable_amount = bill.payable_amount + query.payable_settled_amount
            bill.save()
        query.bill_id = bill.id
        query.save()


def checkout_merchant_sxf_subsidy():
    '''校验商户随行付通道'''
    print('%s: checkout_merchant_sxf_subsidy' % time.ctime())
    merchant_set = Merchant.objects.filter(subsidy_channel_id=2, is_sxf_subsidy=0)
    for merchant in merchant_set:
        try:
            result = check_shop_can_subsidy(merchant.ruiyinxinMerchantID, 'sxf_tq')
            if result['is_can_subsidy'] == 1:
                merchant.subsidy_channel_id = 3
                merchant.is_sxf_subsidy = 1
                merchant.save()
                print(f'{merchant.id}开通随行付成功')
            else:
                print(f'{merchant.id}开通随行付失败')
        except:
            pass



if __name__ == '__main__':
    pass
    # start_time = '2022-08-26 00:00:00'
    # a = 0
    # while True:
    #     if a == 90:
    #         break
    #     end_time = (datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S")
    #     synchronization_kl_order1(start_time, end_time)
    #     start_time = end_time
    #     a += 1
    # synchronization_kl_order2()
    # queryset = MerchantBill.objects.filter(bill_state=1, receipts_time__gt='2023-02-20 00:00:00').order_by('receipts_time')
    # for query in queryset:
    #     business_no = query.merchant.wyfMerchantID
    #     syn_tool('2023-02-20 00:00:00', 92, business_no)
    # syn_tool7()
    # syn_tool('2023-02-01 00:00:00', 200, '1005490199')
    # delete_order()
    # staff_qrcode_status('c82dd8f406e7ed80f7bcfdc02b2bdb4dbf011aee73c814ef83f30e1d52af07a4')
    settlement_residentialhostel_order()
    # settlement_order()
    # sms_settlement_order_email()
    # checkout_merchant_sxf_subsidy()